<?php

/**
 * Description of AuthorAddController
 *
 */
class GrapheController {

    function __construct() {
        
    }

    /**
     * Function saveCSV
     */
    public static function save() {

        // TODO switch
        // TODO notempty
        if (isset($_POST['action']) && ($_POST['action'] == "save")) {

            if (!$_FILES['csv']['error'] > 0) {

                $valide_extensions = array('jpg', 'jpeg', 'gif', 'png', 'csv', 'xsl');
                $extension_upload = strtolower(substr(strrchr($_FILES['csv']['name'], '.'), 1));
                $idProjet = $_POST['select-project-add'];
                $nameService = ($_POST['select-project-type'] == "data") ? "data" : "service";
                $fileNewName = $nameService . "-" . $idProjet . "-" . date("ymj-his") . '.' . $extension_upload;


                if (in_array($extension_upload, $valide_extensions)) {

                    // TODO Parameter
                    $resultat = move_uploaded_file($_FILES['csv']['tmp_name'], "tmp/files/" . $fileNewName);

                    $csv = new CSV('null', $fileNewName, Authentification::getCurrentMemberId(), $idProjet);

                    if ($_POST['select-project-type'] == "data") {
                        try {
                            Log::createLog("try in saving csv ");
                            $csv->save("data");
                        } catch (Exception $e) {
                            Log::createLog("error in saving csv " . $e);
                        }
                    }

                    else
                        $csv->save("service");

                }
            }
            else {

                echo '<META HTTP-EQUIV="Refresh" CONTENT="0;URL=main.php?page=0&error">'; 
            }
        }
    }

    public static function getProjects() {
        return Project::getProjectsOfMember(Authentification::getCurrentMemberId(), Authentification::getCurrentMemberStatut());
    }

    public static function getCurrentProject() {
        if (isset($_GET['project']) && ($_GET['project'] != null)) {

            $id_project = $_GET['project'];

            $projects = GrapheController::getProjects();
            $i = 0;
            while ($i < count($projects) && $projects[$i]->getId() != $id_project)
                $i++;
            return ($i == count($projects)) ? null : $projects[$i];
        } else {
            $projects = GrapheController::getProjects();
            return $projects[0];
        }
    }

    public static function getProjectsForSelectedList() {
        $projets = GrapheController::getProjects();
        $ul = '<ul class="dropdown-menu">';
        foreach ($projets as $project) {
            $ul .= '<li><a href="main.php?page=0&project=' . $project->getId() . '">' . $project->getProjectName() . '</a></li>';
        }
        $ul .= '</ul>';

        return $ul;
    }

}

?>
